/**
 * 
 */
package com.xb.concurrent.blockqueue;

import java.util.ArrayList;

/**
 * @author kexue
 *
 */
public class BlockBufferSynchronized<T> {

	private ArrayList<T> list;
	private int capacity;
	private Object lock = new Object();

	public BlockBufferSynchronized(int capacity) {
		this.capacity = capacity;
		list = new ArrayList<T>(capacity);
	}

	public boolean put(T ele) throws InterruptedException {
		boolean addInd = false;
		synchronized (lock) {
			while (capacity == list.size()) {
				lock.wait();
			}
			addInd = list.add(ele);
			lock.notifyAll();
		}
		return addInd;
	}

	public <T> T take() throws InterruptedException {
		T t = null;
		synchronized (lock) {
			while (0 == list.size()) {
				lock.wait();
			}
			int index = list.size() - 1;
			t = (T) list.get(index);
			list.remove(index);
			lock.notifyAll();
		}
		return t;
	}

}
